package com.milepost.messagepush.task;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.milepost.messagepush.common.constant.HljucmConstant;
import com.milepost.messagepush.common.enums.ApplicationType;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Created by Ruifu Hua on 2020/2/16.
 * 定时获取access_token，access_token 7200s失效，每7000s获取一次
 */
@Component
@RequiredArgsConstructor
public class GetAccessToken {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final RestTemplate restTemplate;

    private final HljucmConstant hljucmConstant;

    /**
     * 定时获取oa和报修的access_token
     * initialDelay：Spring IoC 容器初始化后，第一次延迟的时间，单位为ms，
     * fixedDelay：从上一个任务完成到下一个任务开始的间隔，单位为ms，
     */
    @Scheduled(initialDelay = 1000, fixedDelay = 6000000)
    public void getAccessToken() {

        try {
            HljucmConstant.oaToken = getToken(restTemplate, ApplicationType.OA.getValue());
            logger.info("获取到oa应用的token=" + HljucmConstant.oaToken);
        } catch (Exception e) {
            logger.error("获取token异常");
            logger.error(e.getMessage(), e);
        }
    }

    private String getToken(RestTemplate restTemplate, String type) throws Exception {

        String url = hljucmConstant.getOaGetToken();
        logger.info("当前正在获取" + type + "应用的token");
        logger.info("获取token请求的url=" + url);

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        logger.info("获取token返回的statusCode=" + statusCode.value());
        String result = responseEntity.getBody();
        logger.info("获取token返回的body体=" + result);

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = mapper.readValue(result, Map.class);
        String errcode = (Integer) map.get("errcode") + "";
        if (!errcode.equals("0")) {
            //失败
            throw new Exception("获取token失败，返回的body体=" + result);
        }

        return (String) map.get("access_token");
    }

}
